﻿
-- Add a PK/clustered index to UDS_Flow_Postil table
IF object_id(N'dbo.PK_UDS_Flow_Postil') IS NOT NULL
    ALTER TABLE dbo.UDS_Flow_Postil DROP CONSTRAINT [PK_UDS_Flow_Postil];
GO
ALTER TABLE dbo.UDS_Flow_Postil ADD CONSTRAINT [PK_UDS_Flow_Postil] PRIMARY KEY NONCLUSTERED (Postil_ID);
GO

IF EXISTS (SELECT 1 FROM sys.indexes WHERE [name] = 'CX_UDS_Flow_Postil')
    DROP INDEX [CX_UDS_Flow_Postil] ON dbo.UDS_Flow_Postil;
CREATE CLUSTERED INDEX [CX_UDS_Flow_Postil] ON dbo.UDS_Flow_Postil (Doc_ID asc);
GO


-- Delete orphan data from the table first
DELETE FROM dbo.UDS_Flow_Postil WHERE Doc_ID NOT IN
(
    SELECT Doc_ID FROM dbo.UDS_Flow_Document
);
GO


-- Add a FK to UDS_Flow_Postil.Doc_ID column
IF object_id(N'dbo.[FK_UDS_Flow_Postil_DocID]') IS NOT NULL
    ALTER TABLE [dbo].[UDS_Flow_Postil] DROP CONSTRAINT [FK_UDS_Flow_Postil_DocID];
ALTER TABLE [dbo].[UDS_Flow_Postil] ADD CONSTRAINT [FK_UDS_Flow_Postil_DocID] FOREIGN KEY (Doc_ID) REFERENCES dbo.UDS_Flow_Document(Doc_ID);
GO
